function delRow(btn){
    var ta = document.getElementById("table");
    var tr = btn.parentNode.parentNode
    ta.deleteRow(tr.rowIndex);
}


function updateRow(btn){
  //获取数量所在行
  var tr = btn.parentNode.parentNode;
  var num = tr.cells[2];
 
  // var num = document.getElementById("num");
  //判断当前是否为数字
  if(!isNaN(Number(num.innerHTML))){
    //输入新的值
   num.innerHTML = "<input type ='text' value=' "+num.innerHTML+"' onblur='updateSave(this)' />";
  }
  

}

function updateSave(val){
  // 获取修改后的值  
  var tr = val.parentNode.parentNode;
  var num = val.parentNode;

  // var tr = btn.parentNode.parentNode;
  var onevalue = tr.cells[4];
  var allvalue = tr.cells[5];

  //保存修改后的值
  num.innerHTML = val.value;
  // console.log(tr,val.value);
  allvalue.innerHTML = accMul(num.innerHTML,onevalue.innerHTML);
}


//////////////////////
function addBook(){
    //增添书籍
    var ta = document.getElementById("table");

      if(document.getElementById("bookname").value==''){
        alert('书名不能为空');
        // prompt('请输入您的姓名:');
      }
      else if(document.getElementById("writer").value==''){
        alert('作者不能为空');
      }
      else if(document.getElementById("booknum").value==''){
        alert('数量不能为空');
      }
      
      else if(isNaN(Number(document.getElementById("booknum").value))){
        alert('数量不能为非数字');
      }
      else if(document.getElementById("press").value==''){
        alert('出版社不能为空');
      }
      else if(document.getElementById("price").value==''){
        alert('单价不能为空');
      }
      else if(isNaN(Number(document.getElementById("price").value))){
        alert('数量不能为非数字');
      }
      else{
         //添加行
        var tr = ta.insertRow(1);
        // 添加单元格内容    
        var cell0 = tr.insertCell(0);
        cell0.innerHTML = document.getElementById("bookname").value;

        var cell1 = tr.insertCell(1);
        cell1.innerHTML = document.getElementById("writer").value;

        var cell2 = tr.insertCell(2);
        cell2.innerHTML = document.getElementById("booknum").value;

        var cell3 = tr.insertCell(3);
        cell3.innerHTML = document.getElementById("press").value;

        var cell4 = tr.insertCell(4);
        cell4.innerHTML = document.getElementById("price").value;

        var cell5 = tr.insertCell(5);
        cell5.innerHTML = accMul(cell2.innerHTML,cell4.innerHTML);
         
        var cell6 = tr.insertCell(6);
        cell6.innerHTML = " <input type='button' name='' id='updata' value='修改数量' onclick='updateRow(this)'>    <input type='button' name='' id='del' value='删除' onclick='delRow(this)'>"

      }
      
}


// 用来得到精确的浮点相乘
function accMul(num1, num2) {
	var m = 0,
		s1 = num1.toString(),
		s2 = num2.toString();
	try {
		m += s1.split(".")[1].length  //获取小数点后的长度m
	} catch (e) {};
	try {
		m += s2.split(".")[1].length
	} catch (e) {};
    //将两数去掉小数点后相乘，然后除以10的m次方
	return (Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)).toFixed(2);
    
}
